<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form">
      <el-form-item label="权限">
        <div class="vab-tree-border">
          <el-tree
            ref="tree"
            :data="list"
            :default-checked-keys="[]"
            :default-expanded-keys="[]"
            node-key="path"
            :props="props"
            show-checkbox
          >
            <template #default="{ data }">
              <span>{{ data.title }}</span>
            </template>
          </el-tree>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doRule } from '@/api/authRole'
  import { getTree } from '@/api/authRule'

  export default {
    name: 'Edit',
    data() {
      return {
        form: {},
        title: '',
        dialogFormVisible: false,
        id: '',
        list: [],
        rule: [],
        props: {
          label: 'name',
          children: 'children',
        },
      }
    },
    watch: {
      dialogFormVisible: {
        handler(newVal) {
          if (newVal) {
            this.getTree()
          }
        },
        immediate: true,
      },
    },
    methods: {
      showRule(row) {
        this.title = '设置权限'
        this.id = row.id
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        // 具体业务请自行调整
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const tree = this.$refs.tree.getCheckedNodes().map((val) => val.id)
            this.doRule(this.id, tree)
            this.$emit('fetch-data')
            this.close()
          }
        })
      },
      async doRule(roleId, rule) {
        const { msg } = await doRule(roleId, rule)
        this.$baseMessage(msg, 'success', 'vab-hey-message-success')
      },
      async getTree() {
        const { data } = await getTree()
        this.list = data.list
      },
    },
  }
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    height: 400px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }
</style>
